package com.atguigu.Threads;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 方法四：线程池创建多线程，JDK 5.0 提供了线程池相关的API:ExecutorService和Excutors
 * 1.ExcutorsServeice真正的线程池接口。常见子类ThreadPoolExecutor
 *  1.1.void execute(Runnalb command):执行任务/命令没有返回值
 *  1.2.<T>Future</T>sumbit(Callable<T> tast)执行Callable接口，有返回值,一般用来执行Call
 *  1.3.void shutdown()关闭连接池
 * 2.Excutors,工具类，线程池的工厂类，用于创建并返回不同类型的线程池
 *  2.1.Excutors.newCachedThreadPool():创建并返回不同类型的线程池
 *  2.2.Executors.newFixedThreadPool(int n):创建一个可根据需要创建线程的线程池
 *  2.3.Executors.newSingleThreadExecutor():创建一个只有一个线程的线程池
 *  2.4.Executors.newScheduledThreadPool(int n):创建一个线程池，它可安排给定延迟后运行命令或者定期地执行
 *
 * @author xiaoqi
 * @data 2021/04/08 10:42
 */
class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
class NumberThread2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 1){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //创建线程池，service为接口，修改属性需要强制转换为ThreadPoolExcutor类型地对象
        ExecutorService service = Executors.newFixedThreadPool(10);
        System.out.println(service.getClass());
        service.execute(new NumberThread1());//参数为Runnable
        service.execute(new NumberThread2());//参数为Runnable
        //关闭线程
        service.shutdown();
//        service.submit(),参数为Callable

    }
}
